/**
 * -----------------------------------
 * Copyright (c) 2021-2025
 * All rights reserved, Designed By www.linfengtech.cn
 * 林风社交论坛商业版本请务必保留此注释头信息
 * 商业版授权联系技术客服	 QQ:  3582996245
 * 严禁分享、盗用、转卖源码或非法牟利！
 * 版权所有 ，侵权必究！
 * -----------------------------------
 */
package io.linfeng.modules.app.controller;

import io.linfeng.common.exception.LinfengException;
import io.linfeng.common.utils.Constant;
import io.linfeng.common.utils.FileCheckUtil;
import io.linfeng.common.utils.R;
import io.linfeng.modules.oss.factory.OSSFactory;
import io.linfeng.modules.oss.entity.SysOssEntity;
import io.linfeng.modules.oss.service.SysOssService;
import io.linfeng.modules.sys.service.SysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;

/**
 * APP文件上传
 *
 */
@RestController
@RequestMapping("app/common")
@Api(tags = "移动端——文件上传")
public class AppOssController {

	@Value("${cloudstorage.max-size}")
	private Long maxSize;

	@Value("${linfeng.path.image}")
	private String imagePath;

	@Value("${linfeng.path.file}")
	private String filePath;

	@Value("${linfeng.path.video}")
	private String videoPath;

	@Autowired
	private SysOssService sysOssService;

	@Autowired
	private SysConfigService sysConfigService;


	@ApiOperation("上传文件")
	@PostMapping("/upload")
	public R upload(@RequestParam("Image") MultipartFile file) {
		if (file.isEmpty()) {
			throw new LinfengException("上传文件不能为空");
		}
		FileCheckUtil.checkSize(maxSize, file.getSize());
		//如果本地存储开启，则走本地存储
		String storageMethod = sysConfigService.getValue(Constant.STORAGEURL_METHOD);

		if(storageMethod.equals("1")){
			String fileName = file.getOriginalFilename();
			int index = fileName.lastIndexOf(".");
			if (index == -1) {
				throw new LinfengException("文件格式错误");
			}
			boolean isImg = FileCheckUtil.checkFileIsImage(fileName);
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ROOT);
			String dateFolder = dateFormat.format(new Date());
			String suffixName = fileName.substring(index).toLowerCase(Locale.ROOT);
			fileName = UUID.randomUUID() + suffixName;
			File files;
			if(isImg){
				files = new File(imagePath + dateFolder+ File.separator + fileName);
			}else{
				files = new File(videoPath + dateFolder+ File.separator + fileName);
			}

			if (!files.getParentFile().exists()) {
				if (!files.getParentFile().mkdirs()) {
					throw new LinfengException("文件夹创建失败");
				}
			}
			try {
				file.transferTo(files);
			} catch (IOException e) {
				e.printStackTrace();
				return R.error("文件上传失败");
			}
			String res;
			String url = sysConfigService.getValue(Constant.LOCAL_STORAGEURL_URL);
			if(isImg){
				res=  url + "resource/image/" + dateFolder + "/" + fileName;
			}else{
				res=  url + "resource/video/" + dateFolder + "/" + fileName;
			}
			SysOssEntity ossEntity = new SysOssEntity();
			ossEntity.setUrl(res);
			ossEntity.setCreateDate(new Date());
			sysOssService.save(ossEntity);
			return R.ok().put("result",res);
		}
		//如果未开启本地存储则选择 云存储 上传文件
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		String url;
		try {
			url = OSSFactory.build().uploadSuffix(file.getBytes(), suffix);
		} catch (IOException e) {
			e.printStackTrace();
			return R.error("上传失败");
		}

		//保存文件信息
		SysOssEntity ossEntity = new SysOssEntity();
		ossEntity.setUrl(url);
		ossEntity.setCreateDate(new Date());
		sysOssService.save(ossEntity);

		return R.ok().put("result",url);
	}



}
